package mydessertstore.web.servlet;

import mydessertstore.domain.Account;
import mydessertstore.domain.Product;
import mydessertstore.service.CatalogService;
import mydessertstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SearchProductsServlet extends HttpServlet {

    private static final String SEARCH_PRODUCTS = "/WEB-INF/jsp/catalog/searchProducts.jsp";
    String keyword;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        keyword =  new String(req.getParameter("keyword").getBytes("iso-8859-1"), "utf-8");
        CatalogService catalogService = new CatalogService();
        List<Product> productsBySearch = new ArrayList<Product>();
        productsBySearch = catalogService.searchProductList(keyword);
        HttpSession session = req.getSession();
        session.setAttribute("productsBySearch",productsBySearch);

        Account account;
        account = (Account) session.getAttribute("account");
        if(account!=null) {

            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + " 搜索 “"+keyword+"” 关键词" ;
            logService.insertLogInfo(account.getUsername(), logInfo);
        }
        else{
            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + " 搜索 “"+keyword+"” 关键词" ;
            logService.insertLogInfo("未登录用户", logInfo);
        }

        req.getRequestDispatcher(SEARCH_PRODUCTS).forward(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
